package com.inspur.edp.common.expr.visitor.type;

import com.inspur.edp.common.type.Type;
import com.inspur.edp.common.type.TypeRefer;
import com.inspur.edp.common.type.cache.TypeThreadCache;
import com.inspur.edp.common.type.utils.TypeUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lizhaorui
 * @description TODO
 * @date 2024/7/20 10:33
 */
public class JavaTypeReferConverter {

    private static final Map<String, String> TYPE_MAP = new HashMap<>();

    static {
        TYPE_MAP.put("int", "Integer");
        TYPE_MAP.put("double", "Double");
        TYPE_MAP.put("boolean", "Boolean");
    }


    public static String getJavaClassName(TypeRefer typeRefer) {
        return getJavaClassName(typeRefer, false);
    }


    public static String getJavaClassName(TypeRefer typeRefer, boolean isGenericTypeContext) {
        StringBuilder sb = new StringBuilder();
        Type type = TypeThreadCache.getType(typeRefer);
        String javaClassName = type.getTypeOptCode();
        String typeName = TypeUtil.getTypeCode(javaClassName);
        if (isGenericTypeContext) {
            if (TYPE_MAP.containsKey(typeName)) {
                sb.append(TYPE_MAP.get(typeName));
            } else {
                sb.append(typeName);
            }
        } else {
            sb.append(typeName);
        }
        if (typeRefer.getGenericTypes() != null && typeRefer.getGenericTypes().size() > 0) {
            sb.append("<");
            int index = 0;
            for (TypeRefer childRefer : typeRefer.getGenericTypes()) {
                if (index > 0) {
                    sb.append(",");
                }
                String text = getJavaClassName(childRefer, true);
                sb.append(text);
                index++;
            }
            sb.append(">");
        }
        return sb.toString();
    }

    public static List<String> getImports(TypeRefer typeRefer) {
        List<String> ret = new ArrayList<>();
        Type type = TypeThreadCache.getType(typeRefer);
        String javaClassName = type.getTypeOptCode();
        ret.add(javaClassName);
        if (typeRefer.getGenericTypes() != null && typeRefer.getGenericTypes().size() > 0) {
            for (TypeRefer childRefer : typeRefer.getGenericTypes()) {
                List<String> childList = getImports(childRefer);
                ret.addAll(childList);
            }
        }
        return ret;
    }


}



